package com.junit;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hcfly.utils.ESClient;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.junit.Test;

import java.io.IOException;

public class MatchQueryDemo {

    private static final ObjectMapper mapper = new ObjectMapper();
    private static final String index = "fruit";
    private static final String type = "species";
    private static final RestHighLevelClient client = ESClient.getClient();

    @Test
    public void matchQuery() throws IOException {
        SearchRequest  request  = new SearchRequest(index);
        request.types(type);
        SearchSourceBuilder builder = new SearchSourceBuilder();

        builder.query(QueryBuilders.matchQuery("disc", "大又甜，粗又长"));

        request.source(builder);


        SearchResponse resp = client.search(request, RequestOptions.DEFAULT);

        for (SearchHit hit : resp.getHits().getHits()) {
            System.out.println(hit.getSourceAsMap());
        }
        System.out.println(resp.getHits().getHits().length);
    }


    @Test
    public void matchAll() throws IOException {
        SearchRequest request = new SearchRequest(index);
        request.types(type);

        SearchSourceBuilder builder = new SearchSourceBuilder();
        builder.query(QueryBuilders.matchAllQuery());
        builder.size(20);   // math_all查询默认查询10条语句，想要查询更多，就设置size>10
        request.source(builder);


        SearchResponse resp = client.search(request, RequestOptions.DEFAULT);

        for (SearchHit hit : resp.getHits().getHits()) {
            System.out.println(hit.getSourceAsMap());
        }
        System.out.println(resp.getHits().getHits().length);

    }
}
